<template>
  <div class="page-container">
    <div class="page-header">
      <h2>员工管理</h2>
      <p>管理系统中的所有员工信息</p>
    </div>

    <!-- 搜索表单 -->
    <div class="search-form">
      <el-form :model="searchForm" :inline="true">
        <el-form-item label="员工姓名">
          <el-input 
            v-model="searchForm.realName" 
            placeholder="请输入员工姓名"
            clearable
          />
        </el-form-item>
        <el-form-item label="所属部门">
          <el-input 
            v-model="searchForm.department" 
            placeholder="请输入所属部门"
            clearable
          />
        </el-form-item>
        <el-form-item label="职位">
          <el-input 
            v-model="searchForm.position" 
            placeholder="请输入职位"
            clearable
          />
        </el-form-item>
        <el-form-item label="角色">
          <el-select 
            v-model="searchForm.role" 
            placeholder="请选择角色"
            clearable
            style="width: 120px"
          >
            <el-option label="管理员" value="admin" />
            <el-option label="经理" value="manager" />
            <el-option label="员工" value="employee" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 工具栏 -->
    <div class="table-toolbar">
      <div class="toolbar-left">
        <el-button type="primary" @click="handleCreate">
          <el-icon><Plus /></el-icon>
          新增员工
        </el-button>
      </div>
    </div>

    <!-- 数据表格 -->
    <el-table v-loading="loading" :data="tableData" stripe border>
      <el-table-column prop="employeeCode" label="员工编号" width="120" />
      <el-table-column prop="realName" label="员工姓名" width="120" />
      <el-table-column prop="gender" label="性别" width="80" />
      <el-table-column prop="department" label="部门" width="120" />
      <el-table-column prop="position" label="职位" width="120" />
      <el-table-column prop="role" label="角色" width="100">
        <template #default="{ row }">
          <el-tag :type="getRoleTagType(row.role)">{{ formatRole(row.role) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="phone" label="联系电话" width="120" />
      <el-table-column prop="email" label="邮箱" min-width="180" />
      <el-table-column prop="hireDate" label="入职日期" width="120" />
      <el-table-column prop="isActive" label="状态" width="80">
        <template #default="{ row }">
          <el-tag :type="row.isActive ? 'success' : 'danger'">
            {{ row.isActive ? '在职' : '离职' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180" fixed="right">
        <template #default="{ row }">
          <el-button type="primary" link @click="handleEdit(row)">
            <el-icon><Edit /></el-icon>
            编辑
          </el-button>
          <el-button type="danger" link @click="handleDelete(row)">
            <el-icon><Delete /></el-icon>
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="pagination.page"
        v-model:page-size="pagination.pageSize"
        :total="pagination.total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 新增/编辑弹窗 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="600px">
      <el-form ref="formRef" :model="formData" :rules="formRules" label-width="80px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="员工姓名" prop="realName">
              <el-input v-model="formData.realName" placeholder="请输入员工姓名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="登录账号" prop="username">
              <el-input v-model="formData.username" placeholder="请输入登录账号" />
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="dialogMode === 'create'">
            <el-form-item label="登录密码" prop="password">
              <el-input v-model="formData.password" type="password" placeholder="请输入登录密码" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="员工编号" prop="employeeCode">
              <el-input v-model="formData.employeeCode" placeholder="请输入员工编号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="性别" prop="gender">
              <el-radio-group v-model="formData.gender">
                <el-radio label="男">男</el-radio>
                <el-radio label="女">女</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="部门" prop="department">
              <el-input v-model="formData.department" placeholder="请输入部门" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="职位" prop="position">
              <el-input v-model="formData.position" placeholder="请输入职位" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="角色" prop="role">
              <el-select v-model="formData.role" placeholder="请选择角色">
                <el-option label="管理员" value="admin" />
                <el-option label="经理" value="manager" />
                <el-option label="员工" value="employee" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="入职日期" prop="hireDate">
              <el-date-picker 
                v-model="formData.hireDate" 
                type="date" 
                placeholder="请选择入职日期"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="phone">
              <el-input v-model="formData.phone" placeholder="请输入联系电话" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="formData.email" placeholder="请输入邮箱" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
          确定
        </el-button>
      </template>
    </el-dialog>

  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { getEmployees, createEmployee, updateEmployee, deleteEmployee } from '@/api/employees'
import { ElMessage, ElMessageBox } from 'element-plus'

const loading = ref(false)
const tableData = ref([])
const submitLoading = ref(false)
const dialogVisible = ref(false)
const dialogMode = ref('create')
const formRef = ref()

const searchForm = reactive({
  realName: '',
  department: '',
  position: '',
  role: ''
})

const pagination = reactive({
  page: 1,
  pageSize: 10,
  total: 0
})

const formData = reactive({
  id: null,
  employeeCode: '',
  username: '',
  password: '',
  realName: '',
  gender: '男',
  phone: '',
  email: '',
  department: '',
  position: '',
  role: 'employee',
  hireDate: '',
  isActive: true
})

const formRules = {
  realName: [{ required: true, message: '请输入员工姓名', trigger: 'blur' }],
  username: [{ required: true, message: '请输入登录账号', trigger: 'blur' }],
  password: [{ required: true, message: '请输入登录密码', trigger: 'blur' }],
  employeeCode: [{ required: true, message: '请输入员工编号', trigger: 'blur' }],
  department: [{ required: true, message: '请输入部门', trigger: 'blur' }],
  position: [{ required: true, message: '请输入职位', trigger: 'blur' }],
  role: [{ required: true, message: '请选择角色', trigger: 'change' }],
}

const dialogTitle = computed(() => dialogMode.value === 'create' ? '新增员工' : '编辑员工')

const getTableData = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.page,
      pageSize: pagination.pageSize,
      ...searchForm
    }
    const res = await getEmployees(params)
    
    // 修复：后端返回的数据结构是 { data: [...], total: 10, page: 1, size: 10 }
    let responseData = res.data
    if (responseData && responseData.data && Array.isArray(responseData.data)) {
      tableData.value = responseData.data
      pagination.total = responseData.total || 0
      console.log('成功加载员工数据:', responseData.data.length, '条')
    } else if (responseData && Array.isArray(responseData)) {
      tableData.value = responseData
      pagination.total = responseData.length
    } else {
      console.warn('API返回的数据格式不正确:', responseData)
      tableData.value = []
      pagination.total = 0
    }
  } catch (error) {
    console.error("获取员工列表失败", error)
    tableData.value = []
    pagination.total = 0
  } finally {
    loading.value = false
  }
}

const formatRole = (role) => {
  const roleMap = {
    admin: '管理员',
    manager: '经理',
    employee: '员工'
  }
  return roleMap[role] || '未知'
}

const getRoleTagType = (role) => {
  const typeMap = {
    admin: 'danger',
    manager: 'success',
    employee: ''
  }
  return typeMap[role] || 'info'
}

const handleSearch = () => {
  pagination.page = 1
  getTableData()
}

const handleReset = () => {
  Object.assign(searchForm, {
    realName: '',
    department: '',
    position: '',
    role: ''
  })
  handleSearch()
}

const handleCreate = () => {
  dialogMode.value = 'create'
  Object.assign(formData, {
    id: null,
    employeeCode: '',
    username: '',
    password: '',
    realName: '',
    gender: '男',
    phone: '',
    email: '',
    department: '',
    position: '',
    role: 'employee',
    hireDate: '',
    isActive: true
  })
  dialogVisible.value = true
}

const handleEdit = (row) => {
  dialogMode.value = 'edit'
  Object.assign(formData, row)
  dialogVisible.value = true
}

const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(`确定要删除员工 "${row.realName}" 吗？`, '确认删除', {
      type: 'warning'
    })
    await deleteEmployee(row.id)
    ElMessage.success('删除成功')
    getTableData()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

const handleSubmit = async () => {
  await formRef.value.validate()
  submitLoading.value = true
  try {
    if (dialogMode.value === 'create') {
      await createEmployee(formData)
      ElMessage.success('新增成功')
    } else {
      await updateEmployee(formData.id, formData)
      ElMessage.success('更新成功')
    }
    dialogVisible.value = false
    getTableData()
  } catch (error) {
    console.error('提交失败:', error)
    ElMessage.error('提交失败')
  } finally {
    submitLoading.value = false
  }
}

const handleSizeChange = (val) => {
  pagination.pageSize = val
  pagination.page = 1
  getTableData()
}

const handleCurrentChange = (val) => {
  pagination.page = val
  getTableData()
}

onMounted(getTableData)
</script>

<style lang="scss" scoped>
.page-header {
  margin-bottom: 20px;
  
  h2 {
    font-size: 24px;
    font-weight: 600;
    color: #333;
    margin-bottom: 8px;
  }
  
  p {
    color: #666;
    font-size: 14px;
  }
}
</style> 